//
//  LoginViewController.m
//  NoneCar
//
//  Created by DongSen on 2018/7/10.
//  Copyright © 2018年 董森森. All rights reserved.
//
#import "DSSendCode.h"
#import "UITextField+DSIndexPath.h"
#import "LoginCodeTableViewCell.h"
#import "AppDelegate.h"
#import "APIManager+Login.h"
#import "SectionHeadView.h"
#import "LoginTableViewCell.h"
#import "LoginHeadView.h"
#import "LoginViewController.h"
#import "LoginFootView.h"

@interface LoginViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)LoginHeadView * headView;
@property (strong, nonatomic)LoginFootView * footView;
@property (strong, nonatomic)LoginTableViewCell * phoneCell;//手机号
@property (strong, nonatomic)LoginCodeTableViewCell * accountCell;
@property (strong, nonatomic)LoginCodeTableViewCell * passwordCell;
@property (strong, nonatomic)LoginCodeTableViewCell * codeCell;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登陆";
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableHeaderView = self.headView;
    [self.tableView registerNib:[UINib nibWithNibName:@"LoginTableViewCell" bundle:nil] forCellReuseIdentifier:@"LoginTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LoginCodeTableViewCell" bundle:nil] forCellReuseIdentifier:@"LoginCodeTableViewCell"];
    [self.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    // Do any additional setup after loading the view from its nib.
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}
-(LoginCodeTableViewCell *)codeCell{
    if (!_codeCell) {
        _codeCell = [self.tableView dequeueReusableCellWithIdentifier:@"LoginCodeTableViewCell"];
        _codeCell.inputTextField.placeholder = @"请输入验证码";
        _codeCell.inputTextField.secureTextEntry = YES;
        _codeCell.inputTextField.delegate = self;
    }
    return _codeCell;

}
-(LoginCodeTableViewCell *)passwordCell{
    if (!_passwordCell) {
        _passwordCell = [self.tableView dequeueReusableCellWithIdentifier:@"LoginCodeTableViewCell"];
        _passwordCell.inputTextField.placeholder = @"请输入密码";
        _passwordCell.inputTextField.secureTextEntry = YES;
        _passwordCell.inputTextField.delegate = self;
    }
    return _passwordCell;
}
-(LoginCodeTableViewCell *)accountCell{
    if (!_accountCell) {
        _accountCell = [self.tableView dequeueReusableCellWithIdentifier:@"LoginCodeTableViewCell"];
        _accountCell.inputTextField.placeholder = @"请输入账号";
        _accountCell.inputTextField.delegate = self;
        _accountCell.inputTextField.secureTextEntry = NO;
    }
    return _accountCell;
}
-(LoginTableViewCell *)phoneCell{
    if (!_phoneCell) {
        _phoneCell = [self.tableView dequeueReusableCellWithIdentifier:@"LoginTableViewCell"];
        _phoneCell.inputTextField.placeholder = @"请输入手机号";
        _phoneCell.inputTextField.delegate = self;
        _phoneCell.inputTextField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneCell.inputTextField.secureTextEntry = NO;
        _phoneCell.canSend = NO;
        [_phoneCell.sendButton addTarget:self action:@selector(sendCode) forControlEvents:UIControlEventTouchUpInside];
    }
    return _phoneCell;
}

- (LoginHeadView *)headView{
    if (!_headView) {
        _headView = [LoginHeadView loadView];
        _headView.frame = CGRectMake(0, 0, kSCREEN_W, 190);
    }
    return _headView;
}
- (LoginFootView *)footView{
    if (!_footView) {
        _footView = [LoginFootView loadView];
        _footView.frame = CGRectMake(0, 0, kSCREEN_W, 150);
        WeakSelf(self);
        _footView.block = ^(BOOL PhoneLogin) {
            weakSelf.phoneCell.inputTextField.text =@"";
            weakSelf.codeCell.inputTextField.text =@"";
            weakSelf.accountCell.inputTextField.text =@"";
            weakSelf.passwordCell.inputTextField.text =@"";
            [[DSSendCode shareTime] clears];
            [weakSelf.tableView reloadData];
        };
        [_footView.loginButton addTarget:self action:@selector(logins) forControlEvents:UIControlEventTouchUpInside];
    }
    return _footView;
}

//发送验证码
-(void)sendCode{
    WeakSelf(self);
    [self.view endEditing:YES];

    [self showLoading];
    NSDictionary * dic =@{@"Mobile":self.phoneCell.inputTextField.text,
                          @"CodeType":@(3)};
    [[APIManager sharedNetManager] PostSendCode:dic sucess:^(NSInteger code, NSDictionary *dict){
        [weakSelf hidloading];
        if ([[dict objectForKey:@"Code"] integerValue]==1){
            [weakSelf showMessage:@"短信验证码已发送"];
            [weakSelf reloadUI];
        }
        else{
            [weakSelf showMessage:[dict objectForKey:@"Message"]];
        }
    } failure:^(NSInteger code, NSError *error) {
        [weakSelf hidloading];
        [weakSelf showNetError];
    }];
}
-(void)reloadUI{
    [[DSSendCode shareTime] sendCodeTime];
    WeakSelf(self);
    [DSSendCode shareTime].block = ^(BOOL start, NSString * time) {
        if (start) {
            weakSelf.phoneCell.canSend = NO;
            weakSelf.phoneCell.sendButton.userInteractionEnabled = NO;
            NSString *strTime = [NSString stringWithFormat:@"%@s重新发送",time];
            weakSelf.phoneCell.sendButton.titleLabel.text = strTime;
            [weakSelf.phoneCell.sendButton setTitle:strTime forState:UIControlStateNormal];
        }
        else{
            weakSelf.phoneCell.canSend = YES;
            weakSelf.phoneCell.sendButton.userInteractionEnabled = YES;
            weakSelf.phoneCell.sendButton.titleLabel.text = @"获取验证码";
            [weakSelf.phoneCell.sendButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        }
    };
}
//账号登陆
-(void)accountLogin{
    WeakSelf(self);
    [self showLoading];
    NSDictionary * dic =@{@"UserAccount":self.accountCell.inputTextField.text,
                           @"UserPassWord":self.passwordCell.inputTextField.text,
                           @"FromMethod":@(3)};
    [[APIManager sharedNetManager] PostAccountLoginAccount:dic sucess:^(NSInteger code, NSDictionary *dict) {
        [weakSelf hidloading];
        if ([[dict objectForKey:@"Code"] integerValue]==1) {
            UserInfo *info =[UserInfo mj_objectWithKeyValues:[dict objectForKey:@"Data"]];
            [UserData sharedUserData].user = info;
            [self loginSuccess];
        }
        else{
            [weakSelf showMessage:[dict objectForKey:@"Message"]];
        }
    } failure:^(NSInteger code, NSError *error) {
        [weakSelf hidloading];
        [weakSelf showNetError];
    }];
}
//手机号登陆
- (void)mobileLogin{
    WeakSelf(self);
    [self showLoading];
    NSDictionary * dic =@{@"Moblie":self.phoneCell.inputTextField.text,
                          @"VerifyNumber":self.codeCell.inputTextField.text,
                          @"FromMethod":@(3),
                          };
    [[APIManager sharedNetManager] PostMobileLoginAccount:dic sucess:^(NSInteger code, NSDictionary *dict) {
        [weakSelf hidloading];
        if ([[dict objectForKey:@"Code"] integerValue]==1) {
            UserInfo *info =[UserInfo mj_objectWithKeyValues:[dict objectForKey:@"Data"]];
            [UserData sharedUserData].user = info;
            [self loginSuccess];
        }
        else{
            [weakSelf showMessage:[dict objectForKey:@"Message"]];
        }
    } failure:^(NSInteger code, NSError *error) {
        [weakSelf hidloading];
        [weakSelf showNetError];
    }];
}
- (void)loginSuccess{
    AppDelegate * delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    delegate.tabs.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [UIView transitionWithView:window duration:1 options:UIModalTransitionStyleCoverVertical animations:^{
        [UIApplication sharedApplication].keyWindow.rootViewController = delegate.tabs;
    } completion:^(BOOL finished) {
        
    }];

}

//登陆
-(void)logins{
    [self.view endEditing:YES];
    if (self.footView.accountLogin) {
        if (self.accountCell.inputTextField.text.length<1) {
            [self showMessage:@"请输入账号"];
            return;
        }
        if (self.passwordCell.inputTextField.text.length<1) {
            [self showMessage:@"请输入密码"];
            return;
        }
        [self accountLogin];//账户登陆
    }
    else{
        if (self.phoneCell.inputTextField.text.length!=11) {
            [self showMessage:@"请输入正确的手机号"];
            return;
        }
        if (self.codeCell.inputTextField.text.length<1) {
            [self showMessage:@"请输入验证码"];
            return;
        }
        [self mobileLogin];//手机号登陆
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -- UITableViewDataSource

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 150;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    if (self.footView.accountLogin){
        if(indexPath.row==0){
            return self.accountCell;
        }
        else{
            return self.passwordCell;
        }
    }
    else{
        if(indexPath.row==0){
            return self.phoneCell;
        }
        return self.codeCell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return self.footView;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 52;
}

#pragma mark -- UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * result;
    if (string.length>0) {
        result = [NSString stringWithFormat:@"%@%@",textField.text,string];
    }
    else{
        result =[textField.text substringToIndex:textField.text.length-1];
    }
    if (textField==self.phoneCell.inputTextField){
        if (self.phoneCell.inputTextField.text.length>11&&string.length>0) {
            return NO;
        }
        if (result.length==11) {
            self.phoneCell.canSend = YES;
        }
        else{
            self.phoneCell.canSend = NO;
        }
    }
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (self.footView.accountLogin) {
        if (self.accountCell.inputTextField.text.length>0&&self.passwordCell.inputTextField.text.length>0) {
            self.footView.canCommit = YES;
        }
        else{
            self.footView.canCommit = NO;
        }
    }
    else{
        if (self.phoneCell.inputTextField.text.length==11&&self.codeCell.inputTextField.text.length>0) {
            self.footView.canCommit = YES;
        }
        else{
            self.footView.canCommit = NO;
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
